package cc.lucien.servlet;

import cc.lucien.service.RegisterService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@MultipartConfig(location = "F:\\photo\\temp")
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    RegisterService registerService = new RegisterService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method == null){
            method = "register";
        }
        switch (method){
            case "register":
                resp.sendRedirect("register.jsp");
                break;
            case "success":
                PrintWriter out = resp.getWriter();
                out.write("<h1>register success!</h1>");
                break;
            default:
                HttpSession session = req.getSession();
                session.setAttribute("err", method);
                resp.sendRedirect("register");
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password1 = req.getParameter("password1");
        String password2 = req.getParameter("password2");
        String realname = req.getParameter("realname");
        Part part = req.getPart("img");
        String email = req.getParameter("email");
        String phoneStr = req.getParameter("phone");
        Long phone = Long.parseLong(phoneStr);
        String source = req.getParameter("source");
        String result = registerService.register(username, password1, password2, realname,
                part, email, phone, source);
        resp.sendRedirect("register?method="+result);
    }
}
